library(fixest)
rm(list=setdiff(ls(), "twd")) 
options(warn=-1)


data<-readRDS(paste(twd,"data/made_data/vreg_wgeos_race.rds",sep=""))


## In person 20
data$in_person_primary_20<-ifelse(data$voting_method_200303 == "P",1,0)
## Abs early 20
data$abs_early_primary_20<-ifelse(data$voting_method_200303 %in% c("A","E"),1,0)
## In person 18
data$in_person_general_18<-ifelse(data$voting_method_181106 == "P",1,0)
## Abs early 18
data$abs_early_general_18<-ifelse(data$voting_method_181106 %in% c("A","E"),1,0)
## Take First Difference
data$diff_in_person<-data$in_person_primary_20-data$in_person_general_18
data$diff_abs_early<-data$abs_early_primary_20-data$abs_early_general_18
### get the minimum of the distance to a consolidated (including super sites)
data$distance_realized_min<-apply(cbind(data$distance_realized,data$distancegov1,data$distancegov2),1,min,na.rm=T)
## Difference between assigned and realized distances (in logs and levels)
data$ln_dist_change<-ifelse(data$moved==1,log(data$distance_realized_min)-log(data$distance_assigned),0)
data$lev_dist_change<-ifelse(data$moved==1,data$distance_realized_min-data$distance_assigned,0)
### Difference between assigned and realized size # of assigned voters (in logs and levels)
data$ln_diff_N<-log(data$realized_N)-log(data$assigned_N)
data$lev_diff_N<-data$realized_N-data$assigned_N


### Run regressions


ft1<-feols(diff_in_person~moved+consolidated,data=data,cluster~polling_place_text_name)
ft2<-feols(diff_in_person~moved+consolidated+I(dist_damage_min<500)+I(dist_power_min<500),data=data,cluster~polling_place_text_name)
ft3<-feols(diff_in_person~moved+consolidated+ln_dist_change+ln_diff_N+I(dist_damage_min<500)+I(dist_power_min<500),data=data,cluster~polling_place_text_name)
ft4<-feols(diff_in_person~moved+consolidated+I(dist_damage_min<500)+I(dist_power_min<500)+diff_abs_early,data=data,cluster~polling_place_text_name)
ft5<-feols(diff_in_person~moved+consolidated+ln_dist_change+ln_diff_N+I(dist_damage_min<500)+I(dist_power_min<500)+diff_abs_early,data=data,cluster~polling_place_text_name)
ft6<-feols(diff_abs_early~moved+consolidated,data=data,cluster~polling_place_text_name)
ft7<-feols(diff_abs_early~moved+consolidated+I(dist_damage_min<500)+I(dist_power_min<500),data=data,cluster~polling_place_text_name)
ft8<-feols(diff_abs_early~moved+consolidated+ln_dist_change+ln_diff_N+I(dist_damage_min<500)+I(dist_power_min<500),data=data,cluster~polling_place_text_name)

## Table 1 

log_print(
  esttex(list(ft1,ft2,ft3,ft4,ft5,ft6,ft7,ft8), ci=.95,
       coefstat = "confint",signif.code = NA, keep = c("moved","consolidated","ln_dist_change","ln_diff_N"),
       fitstat = c("n")
       )
  )



